<?php
/**
 * Created by PhpStorm.
 * User: czw
 * Date: 2018/7/11
 * Time: 14:59
 */
namespace app\common\model;

use app\lib\exception\BaseException;
use app\lib\exception\CreateException;
use app\lib\exception\UpdateException;

class UserProductPiece extends BaseModel
{
    public static function createOne($data)
    {
        $model = new self();
        $res = $model->allowField(true)->create($data);
        if (!$res) throw new CreateException();
        return $res;
    }

    public static function updateOne($id, $data)
    {
        $model = new self();
        $res = $model->allowField(true)->save($data, ['id' => $id]);
        if (!$res) throw new UpdateException();
        return $res;
    }

    public static function getByUserId($user_id, $field = '*')
    {
        return self::where('user_id=' . $user_id)->field($field)->select();
    }

    public static function incUserPiece($user_id, $product_id, $piece_id)
    {
        //检查用户有没有碎片
        $user_piece = self::where(['user_id' => $user_id, 'piece_id' => $piece_id])->find();
        $data = ['piece_id' => $piece_id, 'user_id' => $user_id, 'product_id' => $product_id,
            'number'=>1];
        if (empty($user_piece)) {
            //还没有碎片
            self::createOne($data);
        } else {
            //有碎片了,数量+1
            $res = $user_piece->setInc('number');
            if (!$res) {
                throw new BaseException('碎片增加失败');
            }
        }
    }

}